//go:build !windows

package third_program

import (
	net "net/url"
	"os/exec"
	"strings"

	"file_explorer/common/log"
	"file_explorer/common/util"
	"file_explorer/model"
	"file_explorer/service"
)

type apiImpl struct{}

func (a *apiImpl) RunCmd(name string, args ...string) {
	cmd := exec.Command(name, args...)
	err := cmd.Run()
	if err != nil {
		log.Error("run cmd failed, name=%v, args=%v, err=%v", name, args, err)
		return
	}
	log.Debug("run cmd success, name=%v, args=%v", name, args)
	return
}

func (a *apiImpl) OpenFile(path string) {
	a.RunCmd("open", util.FormatPath(path))
}

func (a *apiImpl) OpenPathWithDefaultFileExplorer(path string) {
	a.RunCmd("open", util.FormatPath(path))
}

func (a *apiImpl) OpenUrlsWithDefaultWebExplorer(urls []string) {
	for _, url := range urls {
		if len(url) == 0 {
			continue
		}
		if !strings.HasPrefix(strings.ToLower(url), "http") {
			url = "https://" + url
		}
		if _, err := net.ParseRequestURI(url); err != nil {
			log.Error("parse uri failed, url=%v, err=%v", url, err)
			continue
		}
		a.RunCmd("open", url)
	}
}

func (a *apiImpl) SearchByEverything(keyword string) ([]*model.FileInfo, error) {
	return service.QueryFiles(util.GetHomeDir(), nil)
}
